package com.example.tass.controller;

import cn.tass.SRJ1933.devices.inf.TassSignServerApi;
import cn.tass.SRJ1933.devices.params.request.p7Envelop.DecryptP7EnvelopRequest;
import cn.tass.SRJ1933.devices.params.request.p7Envelop.P7EnvelopRequest;
import cn.tass.SRJ1933.devices.params.response.p7Envelop.DecryptP7EnvelopResponse;
import cn.tass.SRJ1933.devices.params.response.p7Envelop.P7EnvelopResponse;
import cn.tass.exceptions.TAException;
import com.example.tass.common.ResultMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class Envelop_3_4 {

    private static String printFormat = "错误码[%d]\n错误消息[%s]\n接口结果： %s\n";
    private static final Logger logger = LoggerFactory.getLogger(Envelop_3_4.class);
    private TassSignServerApi signServerApi;

    public Envelop_3_4(TassSignServerApi signServerApi) {
        this.signServerApi = signServerApi;
    }

    // ///////////////// 3.4 P7数字信封 ///////////////// 

    //3.4.1 编制P7数字信封（内部密钥和内部证书）
    @GetMapping(value = "/p7Envelop")
    public ResultMessage p7Envelop(@RequestBody P7EnvelopRequest request) {
        try {
            P7EnvelopResponse response = signServerApi.p7Envelop(request.getKeyOrCertId(), request.getKeyOrCertIdType(), request.getEncAlgorithm(),
                    request.getData(), request.getCheckCert());
            if (response.getCode() == 0) {
                return ResultMessage.newSuccessResult(response.getEnvelop());
            } else {
                return ResultMessage.newFailureResult("获取数字信封失败");
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }

    // 3.4.2解密P7数字信封（内部私钥）
    @GetMapping(value = "/decryptP7Envelop")
    public ResultMessage decryptP7Envelop(@RequestBody DecryptP7EnvelopRequest request) {
        try {
            DecryptP7EnvelopResponse response = signServerApi.decryptP7Envelop(request.getKeyId(), request.getKeyIdType(),
                    request.getKeyAccessCode(), request.getEnvelop());
            if (response.getCode() == 0) {
                return ResultMessage.newSuccessResult(response.getData());
            } else {
                return ResultMessage.newFailureResult("解密数字信封失败");
            }
        } catch (TAException e) {
            throw new RuntimeException(e);
        }
    }
}
